<?php
/**
 * 登录控制器
 * @Author    紫梦
 * @DateTime  2017-11-18
 * @copyright 响响租车
 * @version   1.0
 */
namespace app\wxapp\controller;
use think\Controller;
use think\Request;
use think\Db;
use app\common\model\RolesNode;
use app\common\request\Curl;
use app\common\model\Admin;
use think\Log;
use app\common\exception\DefinedException;
use app\common\enums\ResultEnum;
use app\common\utils\ResultVOUtil;

class Login extends controller
{

    public function login($user_name='',$password='',$code='')
    {

        if($user_name!='' && $password!='' || $code){
            $admin = [];
            if($user_name!='' && $password!=''){
                $where['user_name'] = $user_name;
                $where['status'] = 1;
                try{

                    $admin = Db::name('admin')->field('id,password,agency_id,role_id')->where($where)->find();
                }catch(\Exception $e){
                    Log::record('user_name查询admin表'.$e->getMessage());
                    return ResultVOUtil::error(ResultEnum::LOGIN_ERROR);
                }


            }

            if($code){
                $openId = self::wxLogin($code);
                if(empty($openId['openid'])){
                    return ResultVOUtil::error(ResultEnum::CODE_ERROR);
                }
                try{

                    $model = Db::name('admin')->field('id,password,agency_id,role_id')->where(['wp_openid'=>$openId['openid'],'status'=>1])->find();
                }catch(\Exception $e){
                    Log::record('openId查询admin表'.$e->getMessage());
                    return ResultVOUtil::error(ResultEnum::CODE_ERROR);
                }
                if($model != null){
                    $admin = $model;

                }

            }
            
            if($admin == null){
               return ResultVOUtil::error(ResultEnum::ACCOUNT_ERROR);
            }

            if($code && $user_name!='' && $password!=''){
                if(password_verify($password,$admin['password'])){
                    //写入opid

                    Db::name('admin')->where(['id'=>$admin['id'],'status'=>1])->update(['wp_openid' => $openId['openid']]);

                }else{
                   return ResultVOUtil::error(ResultEnum::PASSWORD_ERROR);
                }
            }else if($user_name!='' && $password!=''){

                if(!password_verify($password,$admin['password'])){

                    return ResultVOUtil::error(ResultEnum::PASSWORD_ERROR);
                }
            }

            try{
              $rolesNode = RolesNode::where(['role_id'=>$admin['role_id']])->select();

            }catch(\Exception $e){
                return ResultVOUtil::error(ResultEnum::PARAM_ERROR);
            }
            if($rolesNode){
                foreach ($rolesNode as $value) {
                    $nodes['nodes'][] = strtolower($value['nodes']['node_value']);
                }                   
            }else{
                $nodes['nodes'][] = [];
            }
            $session = array_merge($admin,$nodes);
            session('admin',$session);
            $data = ['PHPSESSID'=>session_id(),'nodes'=>$nodes];

            return ResultVOUtil::success($data);

        }else{
            return ResultVOUtil::error(ResultEnum::PARAM_ERROR);
        }
    
    }



    /**
     * 请求微信APi
     */
    private static function wxLogin($jscode)
    {
        // 微信登录api
        $appid = 'wx9e103dd9205636fa';
        $secret = 'e4989b418af99197d3d15595ffc29217';
        $apiUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$jscode.'&grant_type=authorization_code';

        $curl = new Curl;
        $curl->url($apiUrl);

        // 任务结果状态
        if ($curl->error()) {
            echo $curl->message();
        } else {
            // 任务进程信息
            $info = $curl->info();
            
            // 任务结果内容
            $content = $curl->data();
        }

        return json_decode($content,true);
                
    }


    public function loginOut()
    {
        //退出登录
        session(null);
        return [
            'code' => 1,
            'msg' => '退出成功'
            ];
    }

    
}